import axios from 'axios'
import { Toast } from 'vant'

let baseURL = ''
if (process.env.NODE_ENV === 'development' || process.env.NODE_ENV === 'uat') {
  baseURL = 'https://bisapi.dev.shijiayun.cn/'
} else {
  baseURL = 'https://bisapi.shijiayun.cn/'
}
const service = axios.create({
  baseURL,
  timeout: 300 * 1000 // request timeout
})

// request interceptor
service.interceptors.request.use(
  config => {
    if (window?.$nuxt?.$store?.state?.auth?.token) {
      config.headers.token = sessionStorage.getItem('token')
    }
    return config
  },
  error => {
    // do something with request error
    console.log(error) // for debug
    return Promise.reject(error)
  }
)


// response interceptor
service.interceptors.response.use(
  /**
   * If you want to get http information such as headers or status
   * Please return  response => response
  */

  /**
   * Determine the request status by custom code
   * Here is just an example
   * You can also judge the status by HTTP Status Code
   */
  response => {
    // if the custom code is not 200, it is judged as an error.
    const res = response.data
      return Promise.resolve(res)
    if (response.status === 200) {
      return Promise.resolve(res)
    } else {
      console.warn(response)
      return Promise.resolve(res)
    }
  },
  error => {
    const errorMessageTime = 2 * 1000
    const errMes = error.response
    if (errMes.status === 400) {
      if (errMes.data.code === "AUTH_FAILED") {
        localStorage.removeItem('token')
        resetRouter()
        router.go('/login')
      } else {
        Toast({
          message: errMes.data.message || 'Error',
          duration: errorMessageTime
        })
      }
      return Promise.reject(errMes.data)
    } else {
      Toast({
        message: errMes.data.message || '服务器错误',
        duration: errorMessageTime
      })
      return Promise.reject(errMes.data)
    }
  }
)

export default service